class VideoClient {
    constructor(serverPort = 41235, serverAddress = 'localhost') {
        this.serverPort = serverPort;
        this.serverAddress = serverAddress;
        this.videoChunks = new Map();
        this.totalChunks = 0;
        this.onVideoComplete = null;
        this.ws = null;
        this.videoInfo = null;
        
        this.initializeWebSocket();
    }

    initializeWebSocket() {
        this.ws = new WebSocket(`ws://${this.serverAddress}:${this.serverPort}`);
        
        this.ws.onopen = () => {
            console.log('WebSocket 连接已建立');
            this.register();
        };
        
        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                
                switch (data.type) {
                    case 'videoInfo':
                        this.videoInfo = data;
                        this.totalChunks = data.totalChunks;
                        console.log(`开始接收视频，总大小: ${data.totalSize} 字节`);
                        break;
                        
                    case 'videoChunk':
                        this.videoChunks.set(data.index, data.data);
                        this.checkVideoComplete();
                        break;
                        
                    case 'videoComplete':
                        console.log('视频传输完成');
                        break;
                }
            } catch (error) {
                console.error('处理服务器消息时出错:', error);
            }
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };
        
        this.ws.onclose = () => {
            console.log('WebSocket 连接已关闭');
        };
    }

    register() {
        if (this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({ type: 'REGISTER' }));
        }
    }

    checkVideoComplete() {
        if (this.videoChunks.size === this.totalChunks) {
            this.assembleAndPlayVideo();
        }
    }

    async assembleAndPlayVideo() {
        try {
            // 按顺序组装视频块
            const videoData = Array.from({ length: this.totalChunks }, (_, i) => {
                const base64Data = this.videoChunks.get(i);
                return Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
            });
            
            const videoBlob = new Blob(videoData, { type: this.videoInfo.mimeType });
            const videoUrl = URL.createObjectURL(videoBlob);
            
            // 触发回调函数
            if (this.onVideoComplete) {
                this.onVideoComplete(videoUrl);
            }
            
            // 清理缓存
            this.videoChunks.clear();
            this.videoInfo = null;
        } catch (error) {
            console.error('组装视频时出错:', error);
        }
    }

    setOnVideoComplete(callback) {
        this.onVideoComplete = callback;
    }
}

// 在浏览器环境中导出
if (typeof window !== 'undefined') {
    window.VideoClient = VideoClient;
}

module.exports = VideoClient;